/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @next/next/no-img-element */
/* eslint-disable react-hooks/exhaustive-deps */
"use client"

import { Button } from "@/components/ui/button";
import { DataTable } from "@/components/ui/data-table";
import
{
    DropdownMenu,
    DropdownMenuCheckboxItem,
    DropdownMenuContent,
    DropdownMenuTrigger
} from "@/components/ui/dropdown-menu";
import { useQuery } from "@tanstack/react-query";
import { ColumnDef, VisibilityState } from "@tanstack/react-table";
import axios from "axios";
import { ChevronDown, Download, Edit, Edit2, Trash2 } from "lucide-react";
import moment from "moment-timezone";
import Link from "next/link";
import { useParams } from "next/navigation";
import { useMemo, useState } from "react";
import { useMeasure } from 'react-use';

export default function ContentTypeListPage()
{
    const { type } = useParams() as { type: string }

    // const containerRef = useRef<HTMLDivElement>(null);
    const [containerRef, { width }] = useMeasure<HTMLDivElement>();
    // const [width, setWidth] = useState(0);


    const { data: schema, isLoading: loadingSchema } = useQuery({
        queryKey: ["content-type", type],
        queryFn: async () => (await axios.get(`/api/content-types/${type}`)).data,
        enabled: !!type,
    })

    const { data: rows = [], refetch } = useQuery({
        queryKey: ["content-list", type],
        queryFn: async () => (await axios.get(`/api/content/${type}`)).data,
        enabled: !!type,
    })

    const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({})

    // Delete handler with confirmation
    const handleDelete = async (id: string) =>
    {
        if (!confirm("Are you sure you want to delete this entry?")) return
        await axios.delete(`/api/content/${type}/${id}`)
        refetch() // Refresh the data after delete
    }

    // Prepare columns dynamically
    const columns = useMemo<ColumnDef<any, any>[]>(() =>
    {
        if (!schema?.fields) return []

        // Only show fields that are NOT richtext or html
        const validFields = schema.fields.filter((f: any) =>
            !["richtext", "html", 'image', 'file', 'relation'].includes(f.type)
        )

        return [
            ...validFields.map((f: any) => ({
                accessorKey: f.name,
                header: f.label,
                cell: (info: any) =>
                {
                    const val = info.getValue()
                    // For images: show preview
                    if (f.type === "image" && typeof val === "string" && val.startsWith("http"))
                        return (
                            <img
                                src={val}
                                alt={f.label}
                                className="max-h-16 max-w-xs rounded shadow border"
                                style={{ objectFit: "cover" }}
                            />
                        )

                    // For files: show download button
                    if (f.type === "file" && typeof val === "string" && val.startsWith("http"))
                        return (
                            <a
                                href={val}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="inline-flex items-center gap-1 text-blue-600 hover:underline"
                                download
                            >
                                <Download className="w-4 h-4" />
                                Download
                            </a>
                        )

                    // For booleans
                    if (typeof val === "boolean") return val ? "Yes" : "No"
                    // For objects with ID
                    if (typeof val === "object" && val?.id) return val.id
                    // For all else
                    return val ?? ""
                },
            })),
            {
                id: "status",
                header: "Status",
                cell: ({ row }: any) => (
                    <div className="flex gap-2">
                        <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${row.original.status === "Published"
                            ? "bg-green-100 text-green-800"
                            : row.original.status === "Draft" ? "bg-yellow-100 text-yellow-800" : "bg-blue-100 text-blue-800"}`}>
                            {row.original.status}
                            {row.original.status === "Scheduled" ? ` on ${moment(row.original.schedule).format("MMM D, YYYY")}` : ""}
                        </span>
                    </div>
                ),
                enableHiding: false,
            },
            {
                id: "actions",
                header: <p className="text-end px-2">Actions</p>,
                cell: ({ row }: any) => (
                    <div className="flex gap-2 ml-auto w-[100px] justify-end">
                        <Link
                            href={`/admin/content/${type}/${row.original.id}`}
                            className="text-blue-600 hover:bg-blue-50 rounded-full p-2 transition"
                            title="Edit"
                        >
                            <Edit2 className="w-4 h-4" />
                            <span className="sr-only">Edit</span>
                        </Link>
                        <button
                            onClick={() => handleDelete(row.original.id)}
                            className="text-red-600 hover:bg-red-50 rounded-full p-2 transition"
                            title="Delete"
                        >
                            <Trash2 className="w-4 h-4" />
                            <span className="sr-only">Delete</span>
                        </button>
                    </div>
                ),
                enableHiding: false,
            },
        ]
    }, [schema, type])

    if (loadingSchema) return <div className="p-8">Loading schema…</div>

    return (
        <div className="p-8 w-full">
            <div ref={containerRef} className="flex items-center justify-between mb-6">
                <h1 className="text-2xl font-bold">{schema?.label} List</h1>
                <div className="flex gap-3">
                    {/* Field selector */}
                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <Button variant="outline" size="sm" className="gap-1">
                                Columns <ChevronDown className="w-4 h-4" />
                            </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent>
                            {schema?.fields?.filter((f: any) => !["richtext", "html"].includes(f.type))
                                .map((f: any) => (
                                    <DropdownMenuCheckboxItem
                                        key={f.name}
                                        checked={columnVisibility[f.name] !== false}
                                        onCheckedChange={checked =>
                                        {
                                            setColumnVisibility(cv => ({
                                                ...cv,
                                                [f.name]: checked,
                                            }))
                                        }}
                                    >
                                        {f.label}
                                    </DropdownMenuCheckboxItem>
                                ))}
                        </DropdownMenuContent>
                    </DropdownMenu>
                    <Link href={`/admin/content/${type}/new`}>
                        <Button size="sm" className="px-8">
                            <Edit className="w-4 h-4" />
                            New {schema?.label}
                        </Button>
                    </Link>
                </div>
            </div>

            {
                width > 0 && <div style={{ width: `${width}px` }} className={`overflow-hidden`}>
                    <DataTable
                        columns={columns}
                        data={rows}
                        columnVisibility={columnVisibility}
                        onColumnVisibilityChange={setColumnVisibility}
                    />
                </div> // Only render DataTable if width is set
            }

        </div>
    )
}
